package com.xuliugen.spring.ioc.parse;

import com.xuliugen.spring.ioc.config.Bean;
import com.xuliugen.spring.ioc.config.Property;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xuliugen on 2017/12/13.
 */
public class ConfigManager {

    /**
     * 读取配置文件并返回读取的结果
     * @param path
     * @return
     */
    public static Map<String, Bean> getConfig(String path) {
        //创建一个用于返回的Map对象
        Map<String, Bean> result = new HashMap<>();
        //1、创建解析器
        SAXReader reader = new SAXReader();
        //2、加载配置文件，创建Document对象
        InputStream is = ConfigManager.class.getResourceAsStream(path);
        Document document;
        try {
            document = reader.read(is);
        } catch (DocumentException e) {
            e.printStackTrace();
            throw new RuntimeException("配置文件有错误！请检查xml配置是否正确!");
        }
        //3、定义xPath表达式，取出所有Bean元素
        String xPath = "//bean";
        //4、对Bean元素进行遍历，
        List<Element> elements = document.selectNodes(xPath);
        if (elements != null) {
            elements.forEach(element -> {
                Bean bean = new Bean();
                //将bean的name/class属性封装到Bean对象中
                bean.setName(element.attributeValue("name"));
                bean.setClassName(element.attributeValue("className"));
                //取得Bean元素下所有的Property子元素，将属性name/value/ref封装到Property中
                List<Element> childProperties = element.elements("property");
                if (childProperties != null) {
                    childProperties.forEach(childProperty -> {
                        Property property = new Property();
                        property.setName(childProperty.attributeValue("name"));
                        property.setRef(childProperty.attributeValue("value"));
                        property.setValue(childProperty.attributeValue("ref"));
                        bean.getProperties().add(property);
                    });
                }
                result.put(bean.getName(), bean);
            });
        }
        return result;
    }
}
